import {Direction2D, Vertex2} from "./Direction2D";
import {Length2D} from "./Length2D";
import {roundNumber} from "../number/roundNumber";

let DistanceOfVertexAndLine = (vertex0: Vertex2, path: [Vertex2, Vertex2]) => {
    let [p0, p1] = path;
    let [x0, y0] = p0, [x1, y1] = p1, [xP, yP] = vertex0;
    let [dX, dY] = Direction2D(p0, p1);
    let a = dY, b = -dX, e = -(a * x0 + b * y0);
    let c = dX, d = dY, f = -(c * xP + d * yP);

    let ADBCMinus = a * d - b * c; //always > 0, for dY*dY + dX*dX
    let value0 = d / ADBCMinus, value1 = -b / ADBCMinus;
    let value2 = -c / ADBCMinus, value3 = a / ADBCMinus;
    let joinedValue: Vertex2 = [value0 * -e + value1 * -f,
        value2 * -e + value3 * -f];

    let distance =  Length2D(vertex0, joinedValue);
    let ratio0 = (joinedValue[0] - x0) / dX,
        ratio1 = (joinedValue[1] - y0) / dY;
    let ratio = ratio0;
    if (roundNumber(dX, 5) === 0) ratio = ratio1;

    if (ratio <= 0 || ratio >= 1 ) {
        let distance0 = Length2D(vertex0, p0);
        let distance1 = Length2D(vertex0, p1);
        return Math.min(distance0, distance1);
    }
    return distance;
};

export {DistanceOfVertexAndLine};